//
//  YCChannelCollectionVC.m
//  ChannelChoose
//
//  Created by 唐可雄 on 2019/7/27.
//  Copyright © 2019 swustyc. All rights reserved.
//

#import "YCChannelCollectionVC.h"

#import "YCTextChannelCollectionHeader.h"
#import "YCTextChannelCollectionCell.h"

#define YCMACRO_YCTextChannelCollectionHeader @"YCTextChannelCollectionHeader"
#define YCMACRO_YCTextChannelCollectionCell @"YCTextChannelCollectionCell"

@interface YCChannelCollectionVC ()<UICollectionViewDataSource, UICollectionViewDelegateFlowLayout> {
    YCChannelCollectionVCCompletion _completion;
}

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *channelsEnable;
@property (nonatomic, strong) NSMutableArray *channelsDisable;

@property (nonatomic, strong) UIView *dragView;
@property (nonatomic, strong) NSIndexPath *dragIndexPath;

@end

@implementation YCChannelCollectionVC

#pragma mark - Init

- (instancetype)initWithChannelsEnable:(NSArray *)channelsEnable channelsDisable:(NSArray *)channelsDisable {
    if (self = [super init]) {
        self.channelsEnable = [NSMutableArray arrayWithArray:channelsEnable];
        self.channelsDisable = [NSMutableArray arrayWithArray:channelsDisable];
    }
    return self;
}

#pragma mark - UIViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configView];
}

#pragma mark - View Config

- (void)configView {    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 1, 1) collectionViewLayout:layout];
    self.collectionView.showsHorizontalScrollIndicator = false;
    self.collectionView.showsVerticalScrollIndicator = false;
    self.collectionView.backgroundColor = [UIColor yellowColor];
    [self.collectionView registerClass:[YCTextChannelCollectionCell class] forCellWithReuseIdentifier:YCMACRO_YCTextChannelCollectionCell];
    [self.collectionView registerClass:[YCTextChannelCollectionHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:YCMACRO_YCTextChannelCollectionHeader];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.collectionView];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.collectionView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view.safeAreaLayoutGuide  attribute:NSLayoutAttributeTop multiplier:1 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.collectionView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.view.safeAreaLayoutGuide attribute:NSLayoutAttributeLeading multiplier:1 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.collectionView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self.view.safeAreaLayoutGuide  attribute:NSLayoutAttributeTrailing multiplier:1 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.collectionView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view.safeAreaLayoutGuide  attribute:NSLayoutAttributeBottom multiplier:1 constant:0]];
    
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
    longPress.minimumPressDuration = 0.3f;
    [self.collectionView addGestureRecognizer:longPress];
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return section == 0 ? self.channelsEnable.count : self.channelsDisable.count;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        YCTextChannelCollectionHeader *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:YCMACRO_YCTextChannelCollectionHeader forIndexPath:indexPath];
        header.titleLabel.text = self.sectionTitles[indexPath.section];
        header.subtitleLabel.text = self.sectionSubtitles[indexPath.section];
        return header;
    }
    return nil;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    YCTextChannelCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:YCMACRO_YCTextChannelCollectionCell forIndexPath:indexPath];
    cell.textLabel.text = indexPath.section == 0 ? self.channelsEnable[indexPath.item] : self.channelsDisable[indexPath.item];
    if (indexPath.section == 0 && indexPath.item < self.enableChannelsFixNum) {
        cell.isFixed = YES;
    } else {
        cell.isFixed = NO;
    }
    return cell;
}

#pragma mark - UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(100, 40);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(collectionView.bounds.size.width, 40);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 15, 0, 15);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 10;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 15;
}

#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        // 只剩一个不可删除
        if ([self.collectionView numberOfItemsInSection:0] == 1) {
            return;
        }
        // 第一个不可删除
        id obj = [self.channelsEnable objectAtIndex:indexPath.item];
        [self.channelsEnable removeObjectAtIndex:indexPath.item];
        [self.channelsDisable insertObject:obj atIndex:0];
        [self.collectionView moveItemAtIndexPath:indexPath toIndexPath:[NSIndexPath indexPathForItem:0 inSection:1]];
    } else {
        id obj = [self.channelsDisable objectAtIndex:indexPath.item];
        [self.channelsDisable removeObjectAtIndex:indexPath.item];
        [self.channelsEnable addObject:obj];
        [self.collectionView moveItemAtIndexPath:indexPath toIndexPath:[NSIndexPath indexPathForItem:self.channelsEnable.count - 1 inSection:0]];
    }
}

#pragma mark - UIGestureRecognizer

- (void)longPress:(UILongPressGestureRecognizer *)recognizer {
    CGPoint point = [recognizer locationInView:self.collectionView];
    switch (recognizer.state) {
        case UIGestureRecognizerStateBegan:
            [self dragBegin:point];
            break;
        case UIGestureRecognizerStateChanged:
            [self dragChanging:point];
            break;
        case UIGestureRecognizerStateEnded:
            [self dragEnd];
            break;
        default:
            break;
    }
}

#pragma mark - Drag

-(void)dragBegin:(CGPoint)point{
    NSIndexPath *dragIndexPath = [self indexPathWithPoint:point];
    if (dragIndexPath) {
        if (dragIndexPath.section == 0 && [self.collectionView numberOfItemsInSection:0] > 1 && dragIndexPath.item >= self.enableChannelsFixNum) {
            // 只支持对第一节进行排序，并且第一节元素个数大于1，并且不能固定
            self.dragIndexPath = dragIndexPath;
            
            YCTextChannelCollectionCell *dragCell = (YCTextChannelCollectionCell *)[self.collectionView cellForItemAtIndexPath:dragIndexPath];
            dragCell.isMoving = YES;
            self.dragView = [dragCell snapshotViewAfterScreenUpdates:NO];
            self.dragView.frame = dragCell.frame;
            [self.dragView setTransform:CGAffineTransformMakeScale(1.1, 1.1)];
            [self.collectionView addSubview:self.dragView];
            [self.collectionView bringSubviewToFront:self.dragView];
        }
    }
}

-(void)dragChanging:(CGPoint)point{
    self.dragView.center = point;
    NSIndexPath *targetIndexPath = [self indexPathWithPoint:point];
    if (targetIndexPath && self.dragIndexPath) {
        if (targetIndexPath.section == 0 && targetIndexPath.item >= self.enableChannelsFixNum && ![targetIndexPath isEqual:self.dragIndexPath]) {
            // 只支持对第一节进行排序，且不能是固定的，且不能是自己
            // 更新数据
            id obj = [self.channelsEnable objectAtIndex:self.dragIndexPath.item];
            [self.channelsEnable removeObject:obj];
            [self.channelsEnable insertObject:obj atIndex:targetIndexPath.item];
            // 更新UI
            [self.collectionView moveItemAtIndexPath:self.dragIndexPath toIndexPath:targetIndexPath];
            // 记录
            self.dragIndexPath = targetIndexPath;
        }
    }
}

-(void)dragEnd {
    CGRect endFrame = [self.collectionView cellForItemAtIndexPath:self.dragIndexPath].frame;
    [self.dragView setTransform:CGAffineTransformMakeScale(1.0, 1.0)];
    [UIView animateWithDuration:0.3 animations:^{
        self.dragView.frame = endFrame;
    }completion:^(BOOL finished) {
        [self.dragView removeFromSuperview];
        YCTextChannelCollectionCell *dragCell = (YCTextChannelCollectionCell *)[self.collectionView cellForItemAtIndexPath:self.dragIndexPath];
        dragCell.isMoving = NO;
        self.dragIndexPath = nil;
    }];
}

#pragma mark - Show

- (void)showInViewController:(UIViewController *)vc withCompletion:(void (^)(NSArray * _Nonnull, NSArray * _Nonnull))completion {
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(finishEdit:)];
    _completion = completion;
    [vc presentViewController:[[UINavigationController alloc] initWithRootViewController:self] animated:YES completion:nil];
}

- (void)finishEdit:(UIBarButtonItem *)item {
    _completion(self.channelsEnable, self.channelsDisable);
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - Other

/**
 点所在的IndexPath

 @param point 点
 @return IndexPath
 */
- (NSIndexPath *)indexPathWithPoint:(CGPoint)point {
    NSIndexPath *targeIndexPath = nil;
    
    for (NSIndexPath *indexPath in self.collectionView.indexPathsForVisibleItems) {
        if (CGRectContainsPoint([self.collectionView cellForItemAtIndexPath:indexPath].frame, point)) {
            return indexPath;
        }
    }
    
    return targeIndexPath;
}

@end
